package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"sail/compile"
	"sail/utils/github.com/go-ffmt/ffmt"
	"time"
)

func _testParserSingle(r io.Reader, printTree bool) bool {
	nd, ok := compile.TestParser(r)

	if ok {
		if printTree {
			_, _ = ffmt.P(nd)
		}
	} else {
		fmt.Println("Compile failed!")
	}

	return ok
}

func testParserFolder(base string) {
	fr, err := ioutil.ReadDir(base)
	paths := make([]string, 0)
	if err != nil {
		panic(err)
	}

	for _, f := range fr {
		if !f.IsDir() && path.Ext(f.Name()) == ".sail" {
			paths = append(paths, f.Name())
		}
	}

	for _, p := range paths {
		f, err := os.Open(base + "/" + p)
		if err != nil {
			panic(err)
		}

		fmt.Println("\nparsing " + p + "\n")

		if _testParserSingle(f, true) {
			break
		}
	}
}

func testParserUnit(base string) {
	fr, err := ioutil.ReadDir(base)
	paths := make([]string, 0)
	if err != nil {
		panic(err)
	}

	for _, f := range fr {
		if !f.IsDir() && path.Ext(f.Name()) == ".sail" {
			paths = append(paths, f.Name())
		}
	}

	var failed []string
	var success []string

	for _, p := range paths {
		f, err := os.Open(base + "/" + p)
		if err != nil {
			panic(err)
		}

		fmt.Println("\nparsing " + p + "\n")

		sTime := time.Now().UnixNano()
		if !_testParserSingle(f, false) {
			fmt.Println("Failed!")
			failed = append(failed, f.Name())
			continue
		}
		eTime := time.Now().UnixNano()
		fmt.Printf("Success! (used %d ns) \n\n", eTime-sTime)

		success = append(success, f.Name())
	}

	fmt.Printf("Result (Total %d):\n", len(paths))
	fmt.Printf("\tSuccess (%d):\n", len(success))
	for _, p := range success {
		fmt.Println("\t\t" + p)
	}
	fmt.Printf("\tFailed (%d):\n", len(failed))
	for _, p := range failed {
		fmt.Println("\t\t" + p)
	}
}

func testParserSingle(filepath string) {
	f, err := os.Open(filepath)
	if err != nil {
		panic(err)
	}

	_testParserSingle(f, true)
}

func testParser() {
	// testParserUnit("unit_test/parser/Member/")
	testParserSingle("./test_sources/test.sail")
}
